package com.iamk.feature;

import java.awt.image.BufferedImage;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;

import javax.imageio.ImageIO;

public class FeaturesMSCR {
	BufferedImage bufferedImage;
	File folderImages;
	File folderMask;
	File fileFeatures;

	public FeaturesMSCR(String pathFolder, String pathFolderMask,
			String pathFeatures) {
		// TODO Auto-generated constructor stub
		bufferedImage = null;
		folderImages = new File(pathFolder);
		fileFeatures = new File(pathFeatures);
		folderMask = new File(pathFolderMask);
	}

	public void features() {
		NumberFormat formatter = new DecimalFormat("#.########");
		BufferedWriter bw = null;
		FColorMSCR fColor = null;
		ArrayList<float[]> result;
		String fileName = null;
		String strlabel = null;
//		String[] labels = { "1", "2", "3", "6", "9", "17", "20" };
		try {
			bw = new BufferedWriter(new FileWriter(fileFeatures + ".arff"));
			// Writer header file arff
			bw.write("@RELATION feature\n");
			for (int i = 0; i < 9; i++) {
				bw.write("@ATTRIBUTE f" + (i + 1) + "	REAL\n");
			}
			bw.write("@attribute class {1,2,3,4,5,6,7}\n");
			bw.write("@data\n");
			int count = 0;
			int idImages = 1;
			if (folderImages.isDirectory() && folderImages.exists()
					&& folderMask.isDirectory() && folderMask.exists()) {
				for (int i = 0; i < folderImages.listFiles().length; i++) {
					fileName = folderImages.listFiles()[i].getName().replace(".bmp","");
					// System.out.println(fileName);
					bufferedImage = ImageIO.read(folderImages.listFiles()[i]);
					fColor = new FColorMSCR(bufferedImage,folderMask.listFiles()[i].getPath(), 0);
					
					 System.out.println(folderImages.listFiles()[i].getName()+" "+folderMask.listFiles()[i].getName());
//					 if(!folderImages.listFiles()[i].getName().replace(".bmp", "").equals(folderMask.listFiles()[i].getName().replace(".txt", ""))){
//					 System.out.println(folderImages.listFiles()[i].getName());
//					 }
					result = fColor.extract();
					for (int z = 0; z < result.size(); z++) {
						for (int k = 0; k < result.get(z).length; k++) {
							// System.out.println(result.get(z)[k]);
							if (k == result.get(z).length - 1) {
								bw.write(formatter.format(result.get(z)[k]));
							} else {
								bw.write(formatter.format(result.get(z)[k])
										+ ",");
							}
						}
						bw.write("\n");
					}
				}
				// System.out.println(f.getPath());
			}
			System.out.println(count);
			bw.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private int getIndex(String[] arr, float value) {
		int i = 1;
		for (int j = 0; j < arr.length; j++) {
			if (value==Float.parseFloat(arr[j])){ i=j;
			break;}
		}
		System.out.println(i);
		return i;
	}
}
